package com.azt.provider.impl;

import com.alibaba.druid.util.StringUtils;
import com.azt.api.pojo.File;
import com.azt.api.service.FileService;
import com.azt.model.page.Pagination;
import com.azt.provider.mapper.FileMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class FileServiceImpl implements FileService {
	
	@Autowired
	private FileMapper fm;

	@Override
	public List<File> getMyFiles(Integer userId , Integer isImage) {
		Example exp = new Example(File.class);
		exp.createCriteria().andEqualTo("userId" , userId).andEqualTo("isImage" , isImage).andEqualTo("removed" , File.NO_REMOVED);
		exp.setOrderByClause("id desc");
		return fm.selectByExample(exp);
	}

    @Override
    public void saveOrUpdateFile(File file) {
        if(file.getId() != null) fm.updateByPrimaryKey(file);
		else fm.insert(file);
    }

	@Override
	public void delFile(String fids) {
		if(!StringUtils.isEmpty(fids)){
			for(String id : fids.split(",")){
				fm.delFiles(id);
			}
		}
	}

	@Override
	public Pagination getMyfilesBySearch(int pageno, int pagesize, Map<String, Object> searchMap) {

		Integer userId = Integer.parseInt(searchMap.get("userId").toString());
		Integer isImage = Integer.parseInt(searchMap.get("isImage").toString());
		Page<Object> startPage = PageHelper.startPage(pageno, pagesize);
		List<File> files = getMyFiles(userId , isImage);
		Pagination p = new Pagination(startPage, files);
		p.setList(files);
		return p;
	}
}
